package com.ankicoo.phonograph.controller;

import com.ankicoo.common.response.ResponseBody;
import com.ankicoo.file.service.FileService;
import com.ankicoo.phonograph.handler.AudioRecord;
import org.apache.http.impl.io.IdentityInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/recHandler")
public class RecHandlerController {
    @Autowired
    private FileService fileService;

    private final Map<String,AudioRecord> recordMap = new HashMap<>();

    @GetMapping("/startRecording")
    public ResponseBody<String> startRecording(){
        long currentTimeMillis = System.currentTimeMillis();
        String filePath = "/"+currentTimeMillis+".wav";
        AudioRecord audioRecord = new AudioRecord(filePath);
        this.recordMap.put(String.valueOf(currentTimeMillis),audioRecord);
        audioRecord.captureAudio(); //开始录音的方法
        return ResponseBody.createBySuccess(String.valueOf(currentTimeMillis));
    }

    @GetMapping("/stopRecording/{id}")
    public ResponseBody<String> stopRecording(@PathVariable String id) throws FileNotFoundException {
        if (!this.recordMap.containsKey(id)){
            System.out.println("录音未开始");
            return ResponseBody.createByErrorMessage("录音未开始，或异常终止请重新尝试");
        }
        AudioRecord audioRecord = this.recordMap.get(id);
        audioRecord.closeCaptureAudio(); //关闭录音的方法
        recordMap.remove(id);
        uploadFile( "/"+id+".wav");
        return ResponseBody.createBySuccess();
    }

    private void uploadFile(String filePath) throws FileNotFoundException {
        FileInputStream input = new FileInputStream(new File(filePath));
        fileService.saveFile(filePath.replaceAll("/",""),input);
    }
}
